﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using WebInterface;

namespace WebServices
{
    public class SingleService : ISingleService
    {

        private Timer timer;
        private volatile int changingNumber;
        private volatile int calledTimes;
        private volatile string currentMessage;

        private int status = 0;  //0 :not intial  1: created 2: started 3:stopped

        private string ownData = "";

        private readonly ILogger<SingleService> _logger;
        private readonly ISimpleSingleService _simpleSingleService;

        //private readonly ITransitService _transitService;

        public SingleService(ILogger<SingleService> logger,ISimpleSingleService simpleSingleService)
        {
            _logger = logger;
            _simpleSingleService = simpleSingleService;
            //_transitService = transitService;
            _logger.LogInformation("SingleService start");
            Console.WriteLine("SingleService start");
        }


        

        public void CreateInstance()
        {
            if(status==0)
            {
                changingNumber = 0;
                timer = new Timer(3000);

                _logger.LogInformation("SingleService Created");
                Console.WriteLine("SingleService Created");
                status = 1;
            }

            
        }

        public async Task<bool> SelfDoSomething(string parameter)
        {
            ownData = parameter;
            await Task.Delay(100);
            return true;
        }

        public async Task<bool> OtherServiceDoSomething()
        {
            //var d = await _transitService.DoSomeVeryLongThing("transit set:",1);

            var x = new ScopedService(this);

            ownData = await x.DoSomeVeryLongThing("scope set:", 1);
            await Task.Delay(100);
            return true;
        }


        public async Task Start()
        {
            if(status==1||status==3)
            {
                timer.Elapsed += Timer_Elapsed;
                await Task.Delay(2000);
                timer.Start();
                status = 2;
            }
            
            
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            changingNumber++;
            currentMessage = $"{nameof(SingleService)} ---- {DateTime.Now} --- This is {calledTimes} called. Now is {changingNumber}";
            Console.WriteLine($"{nameof(SingleService)}--- ownData: {ownData}");
        }

        public void Stop()
        {
            if(status==2)
            {
                timer.Stop();
                timer.Elapsed -= Timer_Elapsed;
                status = 3;
            }
            
        }

        public string ReturnCurrentMessage()
        {
            return _simpleSingleService.GetString();
            //return currentMessage;
        }

    }
}
